/*
 * console.c
 *
 * Copyright (C) 2011 - Dr.NP
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * @version console.c 1.0.0
 * @package console
 * @author Dr.NP <np@bsgroup.org>
 * @update 03/18/2011
 */

/**
 * Client console
 *
 * === CHANGELOG ===
 * [03/18/2011] - Creation
 */

#include "bsp.h"

#include "bsp_core.h"
#include "bsp_status.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <err.h>
#include <sys/types.h>

// We need ncurses here
#include <curses.h>

#define DEFAULT_ADDR                            "127.0.0.1"
#define DEFAULT_PORT                            65100

WINDOW *console_window;

void console_interface();
int console_on_data(int, char *, size_t);
void console_on_close(int);

void console_shutdown(int sig)
{
    if (console_window)
    {
        refresh();
        endwin();
    }
    
    fprintf(stderr, "Bye~~~\n");
    
    exit(RTN_SUCCESS);
    
    return;
}

void console_interface()
{
    noecho();
    
    return;
}

int main(int argc, char **argv)
{
    int res = core_init(NULL);
    //char c_addr[64] = DEFAULT_ADDR;
    //u_int16_t c_port = DEFAULT_PORT;
    console_window = NULL;
    
    if (res != RTN_SUCCESS)
    {
        return res;
    }
    
    fprintf(stderr, "Start new window...\n");
    console_window = initscr();
    
    if (!has_colors())
    {
        refresh();
        endwin();
        err(RTN_ERROR_GENERAL, "You terminal does not support color window display\n");
    }
    
    clear();
    cbreak();
    keypad(stdscr, TRUE);
    
    printw("Lines %d / Cols %d", LINES, COLS);
    refresh();
    
    core_loop(console_shutdown);
    
    // My own loop
    while (1)
    {
        getch();
    }
}

int console_on_data(int cnt_id, char *data, size_t len)
{
    fprintf(stderr, "Data recieved %d bytes\n", (int) len);
    debug_hex_data(data, len);
    
    return len;
}

void console_on_close(int cnt_id)
{
    fprintf(stderr, "%d disconnected\n", cnt_id);
    
    return;
}

void * msg_loop(void *arg)
{
    return NULL;
}
